/**
 * @file logger.h
 * @author xc 
 * @brief
 * @version 1.0
 * @date 2025-01-14 
 *
 */
#include <spdlog/spdlog.h>
#include <spdlog/sinks/rotating_file_sink.h>
#include "iostream"
#include "thread"
#include "chrono"
#include "experimental/filesystem"
#include "regex"
#include "iomanip"
#include "spdlog/async.h"
#include "logger.h"
#include "ctime"
#include "sys/time.h"
#include "chrono"
#include <dirent.h>
#include <sys/stat.h>

// std::string log_dir = "/home/leewh/GangDiQingCang_ws/robot_interactive_phase2-20241219/logs";
std::string log_dir = "../logs";
// std::string log_dir = "/home/v2t/Collaborative_Project/log";

//单个日志文件最多3个文件循环，每个文件最多50M，
auto max_size = 50 * 1024 * 1024;//log file max size 5M
auto max_files = 3;//log file max files 3

//文件夹中最大保存的log数量
int max_files_to_keep = 50;

namespace filesystem = std::experimental::filesystem;


double GetCurrentTimestamp()
{
    struct timeval time;
    if (gettimeofday(&time, NULL))
    {
        return 0;
    }
    return ((double)time.tv_sec + (double)time.tv_usec * .000001) * 1000;
}
std::string GetCurrentTimeString()
{
    auto now = std::chrono::system_clock::now();
    std::time_t time = std::chrono::system_clock::to_time_t(now);

    std::tm timeInfo;
    localtime_r(&time, &timeInfo);

    char time_string[26];
    std::strftime(time_string, sizeof(time_string), "%Y_%m_%d_%H_%M_%S", &timeInfo);
    return time_string;
}
logger::logger()
{}
logger::~logger()
{}

void logger::InitLogger()
{
    // Get current time sting and name the log file
    std::string start_time_string = GetCurrentTimeString();
    
    // Create log file
    std::string logfile_name = log_dir + "/daily_log_" + start_time_string + ".log";

    std::cout << "logfile_name:" << logfile_name << std::endl;
    
    auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(logfile_name, max_size, max_files);
    log = std::make_shared<spdlog::logger>("log", rotating_sink);
    
    // Set logger parttern
    // log->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] [Process %P] [%s :%#] [%n] %v");
    log->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] [Process %P] [%s :%#] %v");
    // Set logger level
    log->set_level(spdlog::level::debug);
    log->flush_on(spdlog::level::info);
    // Set the async logger as the default logger
    spdlog::set_default_logger(log);

    SPDLOG_INFO("SPDLOG: logger Initiated.");
    return;
}

void logger::DeleteOldestLogFiles() 
{
    DIR* dir = opendir(log_dir.c_str());
    if (dir == nullptr) {
        std::cout << "Failed to open log directory: " << log_dir;
        return;
    }
    struct dirent* entry;
    std::vector<std::string> logFiles;
    // 遍历日志目录并筛选出日志文件
    while ((entry = readdir(dir)) != nullptr) {
        std::string fileName(entry->d_name);
        if (fileName.find(".log") != std::string::npos) {
            logFiles.push_back(fileName);
        }
    }
    closedir(dir);
    // 如果文件数量超过保留数量，则删除最旧的日志文件
    if (logFiles.size() > max_files_to_keep) {
        std::sort(logFiles.begin(), logFiles.end());
        int filesToDelete = logFiles.size() - max_files_to_keep;
        for (int i = 0; i < filesToDelete; ++i) {
            const std::string filePath = log_dir + "/" + logFiles[i];
            if (remove(filePath.c_str()) != 0) {
                std::cout << "Failed to delete file: " << filePath;
            } else {
                std::cout << "Deleted file: " << filePath;
            }
        }
    }
}

void logger::DestroyLogger()
{
    // Shutdown logger
    SPDLOG_INFO("SPDLOG: logger destroyed.");
    spdlog::shutdown();
    return;
}
